package com.summer.study.leetcode.thread.foobar_115;

import java.util.concurrent.Semaphore;

/**
 * @auther: 杨杰
 * @date: 2019/7/25 14:13
 * @description:
 */
public class SemaphoreDemo {

    private int n;

    public Semaphore seam_foo = new Semaphore(0);

    public Semaphore seam_bar = new Semaphore(1);

    public SemaphoreDemo(int n) {
        this.n=n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            seam_bar.acquire();
            printFoo.run();
            seam_foo.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            seam_foo.acquire();
            printBar.run();
            seam_bar.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SemaphoreDemo demo = new SemaphoreDemo(10);
        Thread t1 = new Thread(() -> {
            System.out.println("foo");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("bar");
        });

        new Thread(() -> {
            try {
                demo.foo(t1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                demo.bar(t2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
